<template>
  <div class="ad-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="ad-search-bar">
      <el-form-item label="广告名称">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入内容"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="danger" plain @click="handleCreate"
          >新建广告</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
      :data="pagedAds"
      style="width: 100%; margin-top: 18px"
      border
      @row-click="handleRowClick"
    >
      <el-table-column prop="name" label="广告名称" min-width="160" />
      <el-table-column label="图片" min-width="100">
        <template #default="scope">
          <el-image
            :src="scope.row.img"
            style="width: 48px; height: 48px"
            fit="cover"
            v-if="scope.row.img"
          />
          <div v-else class="ad-img-placeholder">
            <el-icon><Picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="position" label="广告位值" min-width="120" />
      <el-table-column prop="time" label="时间" min-width="220" />
      <el-table-column prop="clicks" label="点击次数" min-width="100" />
      <el-table-column prop="status" label="状态" min-width="80">
        <template #default="scope">
          <span v-if="scope.row.status === '上线'" style="color: #409eff"
            >上线</span
          >
          <span v-else style="color: #aaa">下线</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140">
        <template #default="scope">
          <el-button
            type="primary"
            link
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            link
            size="small"
            @click="handleOffline(scope.$index, scope.row)"
            >下线</el-button
          >
          <el-button
            type="danger"
            link
            size="small"
            style="color: #f56c6c"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="ad-pagination">
      <el-pagination
        background
        layout="sizes, prev, pager, next, total"
        :total="adList.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        @current-change="handlePageChange"
        @size-change="
          (val) => {
            pageSize = val;
            currentPage = 1;
          }
        "
        style="margin-top: 18px"
      />
      <span class="ad-total"
        >当前条件共检索到
        <span style="color: #f56c6c">{{ adList.length }}</span> 条相关信息</span
      >
    </div>

    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑广告' : '新建广告'"
      width="480px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="newAdForm"
        :rules="formRules"
        ref="adFormRef"
        label-width="90px"
        label-position="left"
      >
        <el-form-item label="广告名称" prop="name" required>
          <el-input v-model="newAdForm.name" placeholder="请输入广告名称" />
        </el-form-item>
        <el-form-item label="广告位置" prop="position" required>
          <el-select v-model="newAdForm.position" placeholder="请选择所属分类">
            <el-option
              v-for="item in positionOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="order" required>
          <el-input
            v-model="newAdForm.order"
            placeholder="请输入排序号"
            type="number"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-button-group>
            <el-button
              :type="newAdForm.status === '上线' ? 'primary' : ''"
              @click="newAdForm.status = '上线'"
              >上线</el-button
            >
            <el-button
              :type="newAdForm.status === '下线' ? 'danger' : ''"
              @click="newAdForm.status = '下线'"
              style="color: #f56c6c"
              >下线</el-button
            >
          </el-button-group>
        </el-form-item>
        <el-form-item label="广告图片" prop="img" required>
          <el-upload
            class="ad-upload"
            action=""
            :show-file-list="false"
            :before-upload="beforeImgUpload"
            :on-change="handleImgChange"
          >
            <div class="ad-upload-box">
              <img
                v-if="newAdForm.img"
                :src="newAdForm.img"
                style="width: 100px; height: 50px; object-fit: cover"
              />
              <div v-else class="ad-upload-placeholder">+</div>
            </div>
          </el-upload>
          <div style="margin-left: 12px; color: #888; font-size: 13px">
            750*380像素<br />仅支持JPG / PNG格式
          </div>
        </el-form-item>
        <el-form-item label="跳转类型" prop="jumpType" required>
          <el-select v-model="newAdForm.jumpType" placeholder="请选择跳转类型">
            <el-option
              v-for="item in jumpTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAd">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showOfflineDialog"
      title="提示"
      width="400px"
      :close-on-click-modal="false"
    >
      <div style="font-size: 16px">
        确定要下线 <span style="color: #f56c6c">{{ offlineName }}</span> 吗?
      </div>
      <template #footer>
        <el-button @click="showOfflineDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmOffline">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showDeleteDialog"
      title="提示"
      width="400px"
      :close-on-click-modal="false"
    >
      <div style="font-size: 16px">
        确定要删除 <span style="color: #f56c6c">{{ deleteName }}</span> 吗?
      </div>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick, onMounted } from "vue";
import { Picture } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const searchForm = ref({ name: "" });

const showDialog = ref(false);
const adFormRef = ref();
const positionOptions = ["首页轮播图", "分类Banner", "活动Banner"];
const jumpTypeOptions = ["无跳转", "商品页", "活动页"];

const newAdForm = reactive({
  name: "",
  position: "",
  order: "",
  status: "下线",
  img: "",
  jumpType: "",
});
const formRules = {
  name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
  position: [{ required: true, message: "请选择广告位置", trigger: "change" }],
  order: [{ required: true, message: "请输入排序号", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  img: [{ required: true, message: "请上传广告图片", trigger: "change" }],
  jumpType: [{ required: true, message: "请选择跳转类型", trigger: "change" }],
};

const isEdit = ref(false);
let editIndex = -1;

// --- 新增变量 ---
const deleteId = ref("");
const offlineId = ref("");
let editId = "";

function handleEdit(index: number, row: any) {
  isEdit.value = true;
  editIndex = index;
  editId = row.id; // 新增
  showDialog.value = true;
  nextTick(() => {
    if (adFormRef.value) adFormRef.value.clearValidate();
    Object.assign(newAdForm, row);
  });
}

function handleCreate() {
  isEdit.value = false;
  showDialog.value = true;
  nextTick(() => {
    if (adFormRef.value) adFormRef.value.resetFields();
    Object.assign(newAdForm, {
      name: "",
      position: "",
      order: "",
      status: "下线",
      img: "",
      jumpType: "",
    });
  });
}

function beforeImgUpload(file: File) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    ElMessage.error("仅支持JPG/PNG格式");
    return false;
  }
  return true;
}
function handleImgChange(file: any) {
  const reader = new FileReader();
  reader.onload = (e) => {
    newAdForm.img = e.target?.result as string;
  };
  reader.readAsDataURL(file.raw);
}

// 广告列表数据
const adList = ref<any[]>([]);

// 获取广告数据（后端接口）
const fetchAds = async () => {
  try {
    const res = await axios.get("http://localhost:3000/jjx/getlunbo");
    if (res.data && res.data.code === 200) {
      adList.value = (res.data.data || []).map((item: any) => ({
        ...item,
        img: item.image, // 适配前端字段
        clicks: item.clickCount,
        order: item.sort,
        time: `${formatTime(item.startTime)}~${formatTime(item.endTime)}`,
      }));
    }
  } catch (e) {
    ElMessage.error("广告数据获取失败");
  }
};

function pad2(n: number) {
  return n < 10 ? "0" + n : "" + n;
}
function formatTime(val: string | Date) {
  if (!val) return "";
  const d = new Date(val);
  return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(
    d.getDate()
  )} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
}

onMounted(() => {
  fetchAds();
});

// 分页相关
const pageSize = ref(5);
const currentPage = ref(1);
const pageSizes = [2, 5, 10];

const pagedAds = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return adList.value.slice(start, start + pageSize.value);
});

const handleSearch = () => {
  const keyword = searchForm.value.name.trim();
  if (!keyword) {
    fetchAds();
    return;
  }
  adList.value = adList.value.filter((ad) => ad.name.includes(keyword));
};
const handleReset = () => {
  searchForm.value.name = "";
  fetchAds();
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const showOfflineDialog = ref(false);
const offlineIndex = ref(-1);
const offlineName = ref("");

function handleOffline(index: number, row: any) {
  offlineIndex.value = index;
  offlineName.value = row.name;
  offlineId.value = row.id; // 新增
  showOfflineDialog.value = true;
}
async function confirmOffline() {
  try {
    if (offlineId.value) {
      await axios.patch(
        `http://localhost:3000/jjx/ad/${offlineId.value}/status`,
        { status: "下线" }
      );
      ElMessage.success("下线成功");
      showOfflineDialog.value = false;
      fetchAds();
    }
  } catch (e) {
    ElMessage.error("下线失败");
  }
}

const showDeleteDialog = ref(false);
const deleteIndex = ref(-1);
const deleteName = ref("");

function handleDelete(index: number, row: any) {
  deleteIndex.value = index;
  deleteName.value = row.name;
  deleteId.value = row.id; // 新增
  showDeleteDialog.value = true;
}
async function confirmDelete() {
  try {
    if (deleteId.value) {
      await axios.delete(`http://localhost:3000/jjx/ad/${deleteId.value}`);
      ElMessage.success("删除成功");
      showDeleteDialog.value = false;
      fetchAds();
    }
  } catch (e) {
    ElMessage.error("删除失败");
  }
}

function handleRowClick(row: any) {
  // 可选：点击行增加点击次数并同步后端
}

// 新增/编辑广告
async function submitAd() {
  adFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    const payload = {
      name: newAdForm.name,
      image: newAdForm.img,
      position: newAdForm.position,
      startTime: new Date(), // 可改为表单选择
      endTime: new Date(), // 可改为表单选择
      status: newAdForm.status,
      sort: Number(newAdForm.order),
      clickCount: isEdit.value
        ? adList.value.find((ad) => ad.id === editId)?.clicks || 0
        : 0,
    };
    try {
      if (isEdit.value && editId) {
        // 编辑
        await axios.put(`http://localhost:3000/jjx/ad/${editId}`, payload);
        ElMessage.success("编辑成功");
      } else {
        // 新增
        await axios.post("http://localhost:3000/jjx/ad", payload);
        ElMessage.success("新增成功");
      }
      showDialog.value = false;
      fetchAds();
    } catch (e) {
      ElMessage.error("操作失败");
    }
  });
}
</script>

<style scoped>
.ad-container {
  background: #fff;
  padding: 24px 18px 0 18px;
  min-height: 600px;
}
.ad-search-bar {
  margin-bottom: 10px;
}
.ad-img-placeholder {
  width: 48px;
  height: 48px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: #bbb;
  font-size: 28px;
}
.ad-pagination {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.ad-total {
  margin-left: 18px;
  color: #888;
  font-size: 15px;
}
.el-pagination.is-background .el-pager li.is-active {
  background: #ff2d2d;
  color: #fff;
  border-radius: 4px;
}
.el-pagination.is-background .el-pager li {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  font-size: 18px;
}
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .btn-next,
.el-pagination.is-background .el-pager li {
  border-radius: 4px;
}
.el-pagination.is-background .btn-prev.is-disabled,
.el-pagination.is-background .btn-next.is-disabled {
  background: #f5f5f5;
  color: #bbb;
}
.el-pagination.is-background .el-select-dropdown__item.selected {
  color: #ff2d2d;
}
.ad-upload-box {
  width: 100px;
  height: 50px;
  border: 1px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafbfc;
  cursor: pointer;
}
.ad-upload-placeholder {
  font-size: 32px;
  color: #bbb;
}
</style>